import { onMounted, onUnmounted } from 'vue'
export function useHtmlFontSizeHook() {
  // rem
  const htmlEl = document.documentElement

  const setHtmlFontSize = () => {
    const oldStyle = {
      htmlFontSize: htmlEl.style.fontSize,
      bodyFontSize: document.body.style.fontSize
    }

    const { clientWidth, clientHeight } = document.body
    console.log('clientWidth', clientWidth, clientHeight)
    let fontSize = 100
    fontSize *= Math.min(clientWidth / 1920, clientHeight / 1080)
    htmlEl.style.fontSize = fontSize + 'px'

    return () => {
      htmlEl.style.fontSize = oldStyle.htmlFontSize
      document.body.style.fontSize = oldStyle.bodyFontSize
    }
  }

  let cancel
  onMounted(() => {
    cancel = setHtmlFontSize()
    window.addEventListener('resize', setHtmlFontSize)
    window.addEventListener('orientationchange', setHtmlFontSize)
    document.body.style.fontSize = '0.16rem'
  })

  onUnmounted(() => {
    cancel && cancel()
    window.removeEventListener('resize', setHtmlFontSize)
    window.removeEventListener('orientationchange', setHtmlFontSize)
  })
}
